<template>
    <el-card class="login-card">
        <h2>Login</h2>
        <el-form :model="form" @submit.prevent="onSubmit">
            <el-form-item label="Username">
                <el-input v-model="form.username" />
            </el-form-item>
            <el-form-item label="Password">
                <el-input type="password" v-model="form.password" />
            </el-form-item>
            <el-button type="primary" @click="onSubmit">Login</el-button>
            <el-button type="primary" @click="onRegister">Register</el-button>
        </el-form>
    </el-card>
</template>

<script setup lang="ts">
    import { ref } from 'vue';
    import { useRouter } from 'vue-router';
    import { useAuth, token, loadUser } from '@/common/useAuth';
    import { ElMessage } from 'element-plus';

    const { login } = useAuth();
    const router = useRouter();

    const form = ref({ username: '', password: '' });
    async function onSubmit() {
        const res = await login(form.value.username, form.value.password);
        if (res && res.success) {
            ElMessage.success('登录成功');
            await loadUser(); 
            // 然后再进行路由跳转
            router.push({ name: 'home' });
            setTimeout(() => {
                router.push({name: "home"});
            }, 1000)
        } else {
            // ElMessage.error("Login failed")
        }
    }

    function onRegister() {
        router.push({ name: 'register' });
    }
</script>

<style scoped>
    .login-card {
        width: 360px;
        margin: 40px auto;
        padding: 20px;
    }
</style>
